package com.caigou.comm.base.utils

import android.content.Context
import com.tencent.mmkv.MMKV
import com.tencent.mmkv.MMKVHandler
import com.tencent.mmkv.MMKVLogLevel
import com.tencent.mmkv.MMKVRecoverStrategic
import java.io.File

/**
 * @author #Suyghur.
 * Created on 2021/09/13
 */
class Prefs private constructor() : MMKVHandler {

    lateinit var userKV: MMKV

    fun init(context: Context) {
        val dir = context.getExternalFilesDir("")!!.absolutePath + File.separator + "app_info"
        MMKV.initialize(context, dir, MMKVLogLevel.LevelInfo)
        MMKV.registerHandler(this)
        userKV = MMKV.mmkvWithID("user_info")
    }

    fun release() {
        MMKV.unregisterHandler()
    }

    override fun onMMKVCRCCheckFail(mmapID: String?): MMKVRecoverStrategic {
        return MMKVRecoverStrategic.OnErrorDiscard
    }

    override fun onMMKVFileLengthError(mmapID: String?): MMKVRecoverStrategic {
        return MMKVRecoverStrategic.OnErrorDiscard
    }

    override fun wantLogRedirecting(): Boolean {
        return true
    }

    override fun mmkvLog(level: MMKVLogLevel?, file: String?, line: Int, function: String?, message: String?) {
        val log = "<${file.toString()}:$line::$function>$message"
        Logger.d(log)
    }

    companion object {
        val instance: Prefs by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            Prefs()
        }
    }
}